//
//  MLAMessageVC.m
//  MagicLampApp
//
//  Created by Zheng on 2018/12/19.
//  Copyright © 2018 zheng.magic.lamp.app. All rights reserved.
//

#import "MLAMessageVC.h"
#import "MLAMessageCell.h"
#import "MLAMessageDetailVC.h"
#import "MLAMessageModel.h"

@interface MLAMessageVC ()

@end

@implementation MLAMessageVC {
    NSMutableArray<MLAMessageModel *> *modelsArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self configTitle:@"消息"];
    
    self.tableView.rowHeight = 78;
    [self.tableView registerClass:[MLAMessageCell class] forCellReuseIdentifier:kMessageCellID];
    
    self.haveRefreshHeader = YES;
    [self loadData];

}

#pragma mark - LoadData
- (void)loadData {
    [super loadData];
    
    [MLAHttpManage postHostType:MLAHttpHostType_Api api:kMessageList params:nil success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        self->modelsArr = [NSMutableArray array];
        self.page++;
        self.haveRefreshFooter = YES;
        self->modelsArr = [NSMutableArray array];
        self->modelsArr = [MLAMessageModel mj_objectArrayWithKeyValuesArray:response[@"lists"]];
        if (self->modelsArr.count < 20) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        [self.tableView reloadData];
        
    } failure:^{
        
    }];
}

- (void)loadMoreData {
    NSDictionary *params = @{@"page":@(self.page)};
    [MLAHttpManage postHostType:MLAHttpHostType_Api api:kMessageList params:params success:^(id  _Nonnull response, NSString * _Nonnull msg) {
        
        self.page++;
        
        if ([response[@"lists"] count] < 20) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
        
        [self->modelsArr addObjectsFromArray:[MLAMessageModel mj_objectArrayWithKeyValuesArray:response[@"lists"]]];
        [self.tableView reloadData];
        
    } failure:^{
        
    }];
}

#pragma mark - tableview datasource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return modelsArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MLAMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:kMessageCellID forIndexPath:indexPath];
    MLAMessageModel *model = modelsArr[indexPath.row];
    cell.model = model;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [super tableView:tableView didSelectRowAtIndexPath:indexPath];
    MLAMessageModel *model = modelsArr[indexPath.row];
    MLAMessageDetailVC *messageDetailVC = [[MLAMessageDetailVC alloc] init];
    messageDetailVC.modelId = model.modelId;
    [self.navigationController pushViewController:messageDetailVC animated:YES];
}


@end
